package com.xmh.nioDemo;


import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIODemo_1 {

    @Test
    public void test1() throws Exception {
//        可以发现这里定义了四种模式：R RW RWD RWS
//
//        r	以只读的方式打开文本，也就意味着不能用write来操作文件
//                Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.
//              仅供阅读。调用结果对象的任何写方法都将导致抛出IOException。
//        rw	读操作和写操作都是允许的
//                Open for reading and writing. If the file does not already exist then an attempt will be made to create it.
//              仅供阅读。调用结果对象的任何写方法都将导致抛出IOException。
//        rws	每当进行写操作，同步的刷新到磁盘，刷新内容和元数据
//                Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.
//              与“rw”一样，Open for读写，并且还要求对文件内容或元数据的每次更新都同步写入底层存储设备
//        rwd	每当进行写操作，同步的刷新到磁盘，刷新内容
//               Open for reading and writing, as with "rw", and also require that every update to the file's content be written synchronously to the underlying storage device.
//              与“rw”一样，Open for读写，并且还要求对文件内容的每次更新都同步地写入底层存储设备。
        RandomAccessFile aFile = new RandomAccessFile("E:\\Spring-Boot-Demo\\src\\main\\resources\\data\\nio-data.txt", "rw");

        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(400);


        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            System.out.println("Read " + bytesRead);
            buf.flip();

            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }

            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        aFile.close();

    }


}
